<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="68px">
      <el-form-item label="姓名" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入姓名"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="城市" prop="city">
        <el-input
          v-model="queryParams.city"
          placeholder="请输入城市"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="等级" prop="grade">
        <el-select v-model="queryParams.grade" placeholder="请选择等级" clearable size="small">
          <el-option
            v-for="dict in gradeOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

   <!-- <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['agent:agent:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['agent:agent:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['agent:agent:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['agent:agent:export']"
        >导出</el-button>
      </el-col>
    </el-row>-->

    <el-table v-loading="loading" :data="agentList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column  align="center" type="index"  />
      <el-table-column label="经纪人编号" align="center" prop="agentCode" />
      <el-table-column label="姓名" align="center" prop="name" />
      <el-table-column label="手机号" align="center" prop="phone" />
      <el-table-column label="城市" align="center" prop="city" />
      <el-table-column label="等级" align="center" prop="grade" :formatter="gradeFormat" />
      <el-table-column label="状态" align="center" prop="status" :formatter="statusFormat" />
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['agent:agent:remove']"
          >{{scope.row.status === 1 ? "冻结账号" : "解冻账号"}}</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['agent:agent:edit']"
          >层级关系</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改经纪人信息对话框 -->
   <!-- <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="上下级关系" prop="agentId">
          <el-input v-model="form.agentId" placeholder="请输入上下级关系" />
        </el-form-item>
        <el-form-item label="微信openid" prop="openid">
          <el-input v-model="form.openid" placeholder="请输入微信openid" />
        </el-form-item>
        <el-form-item label="经纪人编号" prop="agentCode">
          <el-input v-model="form.agentCode" placeholder="请输入经纪人编号" />
        </el-form-item>
        <el-form-item label="头像" prop="headImage">
          <el-input v-model="form.headImage" placeholder="请输入头像" />
        </el-form-item>
        <el-form-item label="姓名" prop="name">
          <el-input v-model="form.name" placeholder="请输入姓名" />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item label="性别">
          <el-select v-model="form.sex" placeholder="请选择性别">
            <el-option label="请选择字典生成" value="" />
          </el-select>
        </el-form-item>
        <el-form-item label="城市" prop="city">
          <el-input v-model="form.city" placeholder="请输入城市" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="form.password" placeholder="请输入密码" />
        </el-form-item>
        <el-form-item label="银行账号" prop="bankAccount">
          <el-input v-model="form.bankAccount" placeholder="请输入银行账号" />
        </el-form-item>
        <el-form-item label="等级">
          <el-select v-model="form.grade" placeholder="请选择等级">
            <el-option
              v-for="dict in gradeOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="form.status" placeholder="请选择状态">
            <el-option
              v-for="dict in statusOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="parseInt(dict.dictValue)"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>-->
    <!--经纪人层级关系弹出框-->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-input
        v-model="treeLable"
        placeholder="请输入"
        clearable
        size="small"
        prefix-icon="el-icon-search"
        style="margin-bottom: 20px"
      />
      <el-tree :data="agentTree"
               :props="defaultProps"
               @node-click="handleNodeClick"
               node-key="id"
               ref="tree"
               :default-expanded-keys="expandedKeys"
               :default-checked-keys="checkedKeys"
               :filter-node-method="filterNode"
               show-checkbox
      ></el-tree>
    </el-dialog>
  </div>
</template>

<script>
import { listAgent, getAgentTree, delAgent, addAgent, updateAgent, exportAgent } from "@/api/agent/agent";

export default {
  name: "Agent",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      //经纪人层级关系
      agentTree:[],
      expandedKeys:[],
      checkedKeys:[],
      treeLable:"",
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      // 经纪人信息表格数据
      agentList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 等级字典
      gradeOptions: [],
      // 状态字典
      statusOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: undefined,
        city: undefined,
        grade: undefined,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      }
    };
  },
  created() {
    this.getList();
    this.getDicts("am_agent_grade").then(response => {
      this.gradeOptions = response.data;
    });
    this.getDicts("am_agent_status").then(response => {
      this.statusOptions = response.data;
    });
  },
  watch:{
    //根据经纪人或者等级赛选
    treeLable(val){
      this.$refs.tree.filter(val);
    }
  },
  methods: {
    /** 查询经纪人信息列表 */
    getList() {
      this.loading = true;
      listAgent(this.queryParams).then(response => {
        this.agentList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 等级字典翻译
    gradeFormat(row, column) {
      return this.selectDictLabel(this.gradeOptions, row.grade);
    },
    // 状态字典翻译
    statusFormat(row, column) {
      return this.selectDictLabel(this.statusOptions, row.status);
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        agentId: undefined,
        openid: undefined,
        agentCode: undefined,
        headImage: undefined,
        name: undefined,
        phone: undefined,
        sex: undefined,
        city: undefined,
        password: undefined,
        bankAccount: undefined,
        grade: undefined,
        status: undefined,
        createTime: undefined
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!=1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加经纪人信息";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
     // const id = row.id || this.ids
      const id = 0
      this.expandedKeys = [row.id];
      this.checkedKeys = [row.id];
      getAgentTree(id).then(response => {
        this.agentTree = response.data;
        console.log(this.agentTree)
        this.open = true;
        this.title = "经纪人层级关系";
      });
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      console.log(data)
      return data.label.indexOf(value) !== -1;
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != undefined) {
            updateAgent(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              }
            });
          } else {
            addAgent(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              }
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const id = row.id || this.ids;
      let status = row.status === 1 ? 0 : 1;
      let message = row.status === 1 ? "解冻成功" : "冻结成功";
      let tips = row.status !== 1 ? "确定解冻该账号吗？解冻后该经纪人恢复佣金获取。" : "是否确认冻结该账号吗?冻结期间该经纪人无佣金！";
      this.$confirm(tips, "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return updateAgent({
            id:id,
            status:status
          });
        }).then(() => {
          this.getList();
          this.msgSuccess(message);
        }).catch(function() {});
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有经纪人信息数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return exportAgent(queryParams);
        }).then(response => {
          this.download(response.msg);
        }).catch(function() {});
    },
    /**
     * 经纪人层级关系点击事件
     * @param data
     */
    handleNodeClick(data) {
     // console.log(data);
    }
  }
};
</script>
